package edu.hncj.seckill.service.impl;

import edu.hncj.seckill.dao.UserMapper;
import edu.hncj.seckill.dao.UserPasswordMapper;
import edu.hncj.seckill.domain.User;
import edu.hncj.seckill.domain.UserPassword;
import edu.hncj.seckill.model.UserModel;
import edu.hncj.seckill.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author anorak
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserPasswordMapper userPasswordMapper;

    @Override
    public UserModel getUserById(String id) {
        // 调用查询方法
        User user = userMapper.selectByPrimaryKey(id);
        UserPassword userPassword = userPasswordMapper.selectByUserId(id);
        return convertFromDataObject(user,userPassword);
    }

    @Override
    public User getUserByTelPhone(String telPhone) {
        return userMapper.selectByTelPhone(telPhone);
    }

    /**
     * 插入用户
     *
     * @param user 用户
     * @return 结果对象
     */
    @Override
    public int insertUser(User user) {
        return userMapper.insert(user);
    }

    /**
     * 更新用户信息
     *
     * @param user 用户
     * @return 结果对象
     */
    @Override
    public int updateUserById(User user) {
        return userMapper.updateByPrimaryKey(user);
    }

    /**
     * 用户对象整合
     * @param user 用户部分数据
     * @param userPassword 用户密码
     * @return 完整的用户对象
     */
    private UserModel convertFromDataObject(User user, UserPassword userPassword){
        if (user == null){
            return null;
        }
        UserModel model = new UserModel();
        model.setId(user.getId());
        model.setName(user.getName());
        model.setGender(user.getGender());
        model.setTelPhone(user.getTelphone());
        if (userPassword != null){
            model.setPassWord(userPassword.getPassword());
        }
        return model;
    }
}
